﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SubSonic;
using ExtAspNet;
using System.IO;


namespace TCMSystem.business.enterprise
{
    public partial class commercial_new : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Module

        /// <summary>
        /// 当前页面所属的模块
        /// </summary>
        public override ModuleType Module
        {
            get
            {
                return ModuleType.BizCommercial;
            }
        }

        #endregion


        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
            if (!CheckPowerNew())
            {
                CheckPowerFailWithPage();
                return;
            }

            btnClose.OnClientClick = ActiveWindow.GetConfirmHidePostBackReference();

        }
        #endregion

        #region Events

        private void SaveItem()
        {
            TblBizEnterprise item = new TblBizEnterprise();
            item.EnterpriseName = tbxEnterpriseName.Text.Trim();
            item.Overview = tbxOverview.Text.Trim();
            // 上传文件、更新图片表并返回图片的文件名
            item.EnterprisePicture = UploadImage();
            //TODO:Picture/Type 用定数
            item.EnterpriseType = 2;

            item.Save(User.Identity.Name);
        }

        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            if (CheckSameName())
            {
                return;
            }

            SaveItem();

            //Alert.Show("添加成功！", String.Empty, ActiveWindow.GetHidePostBackReference());
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }

        private bool CheckSameName()
        {
            SqlQuery q = new Select().From<TblBizEnterprise>();
            q.Where("1").IsEqualTo("1");
            // 商贸市场区分：2
            q.And(TblBizEnterprise.EnterpriseTypeColumn).IsEqualTo(2);

            // 在商贸市场名称中搜索同名项
            q.And(TblBizEnterprise.EnterpriseNameColumn).IsEqualTo(this.tbxEnterpriseName.Text);

            // 满足条件的总共有多少条记录
            if (q.GetRecordCount() != 0)
            {
                this.tbxEnterpriseName.MarkInvalid(String.Format("已经存在商贸市场名为'{0}'的记录，请重新输入！", this.tbxEnterpriseName.Text));
                Alert.ShowInTop(String.Format("已经存在商贸市场名为'{0}'的记录，请重新输入！", this.tbxEnterpriseName.Text));
                return true;
            }

            return false;
        }

        //todo:没反应
        //protected void fileEnterprisePicture_OnLoad(object sender, EventArgs e)
        //{
        //    if (fileEnterprisePicture.HasFile)
        //    {
        //        // 显示控件
        //        imgEnterprisePicture.Hidden = false;
        //        this.btnClearImg.Hidden = false;
        //        imgEnterprisePicture.ImageUrl = fileEnterprisePicture.FileName;
        //    }
        //    else
        //    { // 如果图片ID为空，则隐藏控件
        //        imgEnterprisePicture.Hidden = true;
        //        this.btnClearImg.Hidden = true;

        //    }

        //    //string strFileName = fileEnterprisePicture.FileName;
        //    //if (strFileName == string.Empty)
        //    //{
        //    //    // 如果图片ID为空，则隐藏控件
        //    //    imgEnterprisePicture.Hidden = true;
        //    //    this.btnClearImg.Hidden = true;
        //    //}
        //    //else
        //    //{
        //    //    // 显示控件
        //    //    imgEnterprisePicture.Hidden = false;
        //    //    this.btnClearImg.Hidden = false;
        //    //    imgEnterprisePicture.ImageUrl = strFileName;
        //    //}
        //}





        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns>图片ID</returns>
        private string UploadImage()
        {
            //TODO:文件类型限制没做
            //TODO:参看http://www.extasp.net/forum.php?mod=viewthread&tid=372&highlight=FileUpload

            // 原文件名
            string strOrgImageName = fileEnterprisePicture.ShortFileName;
            if (strOrgImageName == string.Empty)
            {
                return string.Empty;
            }

            // 上传图片的相对路径
            string filePath = GetModuleImagePath();
            // 上传图片的物理路径
            string fileFullPath = Server.MapPath(filePath);
            // 图片扩展名
            string strExtension = strOrgImageName.Substring(strOrgImageName.LastIndexOf(".") + 1, (strOrgImageName.Length - strOrgImageName.LastIndexOf(".") - 1));
            // 图片自动重命名
            string strNewFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "." + strExtension;
            // 上传图片的URL 
            string pictureURL = filePath.Replace("~" + Path.DirectorySeparatorChar,string.Empty) + strNewFileName;
            // 上传图片的物理路径+文件名
            string fileFullName = Server.MapPath(filePath + strNewFileName);

            if (fileEnterprisePicture.HasFile)
            {
                if (!Directory.Exists(fileFullPath))
                {
                    Directory.CreateDirectory(fileFullPath);
                }

                fileEnterprisePicture.SaveAs(fileFullName);
            }

            // 插入图片表
            TblBizPicture item = new TblBizPicture();
            item.PictureName = strNewFileName;
            item.PictureURL = pictureURL;
            item.Save();

            // 返回图片ID
            item = new Select().From<TblBizPicture>()
              .Where(TblBizPicture.PictureNameColumn).IsEqualTo(strNewFileName)
              .ExecuteSingle<TblBizPicture>();

            return item.PictureId.ToString();

        }
        #endregion

    }
}
